package com.my.stock.core;

import java.io.File;
import java.io.IOException;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.apache.commons.math3.stat.descriptive.DescriptiveStatistics;

import com.my.myTradeData.DataSource.Sina;
import com.my.stock.core.HurstEx.HurstResult;

import util.JavaFile;

public class KlineProcess {

	private static String inactiveProduct[] = { "RI", "WH", "wr", "JR", "RS", "bc", "ZC", "PM", "LR", "fb", "rr",
			"bb" };

	private static String uProduct[] = { "(EF)", "(EFP)", "efp", "TAS" };

	private static boolean filterProduct(String product) {

		if (product.length() > 8) {
			return true;
		}

		for (String p : inactiveProduct) {
			if (product.startsWith(p)) {
				return true;
			}

		}

		for (String p : uProduct) {
			if (product.contains(p)) {
				return true;
			}

		}

		return false;
	}

	public static void getDataFromSina() throws IOException, InterruptedException {
		List<String> products = JavaFile.readfile("c:\\tick1\\name.txt");
		for (String p : products) {
			if (p.length() > 0) { // 若是文件，直接打印

				if (filterProduct(p)) {
					continue;
				}

				System.out.println(p);
				Sina.get15mData(p);
				Thread.sleep(8000);

//				String r="";
//				int count=dlist.size();
//				if(count>1000) {
//					count=1000;
//				}
//				
//				for(int i=0;i<count;i++) {
//					r=r+dlist.get(i)+"\r\n";
//					if(dlist.get(i).startsWith("20241125") ||dlist.get(i).startsWith("20241122") ) {
//						break;
//					}
//				}
//				JavaFile.overwritefile(f.getAbsolutePath(), r);
			}
		}

	}

	public static void main1(String[] args) throws IOException, InterruptedException {

		String path = "d:/kline"; // 要遍历的路径
		File file = new File(path);
//
		File[] files = file.listFiles(); // 遍历path下的文件和目录，放在File数组中
		for (File f : files) {
			if (f.isFile()) { // 若是文件，直接打印

				List<String> dataList = JavaFile.readfile(f.getAbsolutePath());

				KlineProcess p = new KlineProcess();

				String last = "";
				String r = "";
				boolean overwrite = false;
				for (int i = 0; i < dataList.size() - 1; i++) {
					String s = dataList.get(i);

					r = r + s + "\r\n";

//							
				}
				r = r + "1" + dataList.get(dataList.size()-1);

//				System.out.println(r);
				JavaFile.overwritefile(f.getAbsolutePath(), r);

//						System.out.println(f + " " + dataList.get(dataList.size() - 1));

			}
		}
	}

	public static void clearFiles() throws IOException {
		String path = "c:/tick"; // 要遍历的路径
		File file = new File(path);
//
		File[] files = file.listFiles(); // 遍历path下的文件和目录，放在File数组中
		for (File f : files) {
			f.deleteOnExit();
		}

		path = "d:/kline2"; // 要遍历的路径
		file = new File(path);
		//
		files = file.listFiles(); // 遍历path下的文件和目录，放在File数组中
		for (File f : files) {
			f.deleteOnExit();
		}
	}

	public static void writeDayKline() throws IOException {
		List<String> products = JavaFile.readfile("c:\\tick1\\name.txt");
		for (String p : products) {
			if (p.length() > 1) { // 若是文件，直接打印

				if (filterProduct(p)) {
					continue;
				}

				List<String> dlist;
				try {
					dlist = JavaFile.readfile("c:/tick/" + p + ".txt");
					KlineProcess kline = new KlineProcess();

					for (String s : dlist) {

						kline.timeLineAllInfo(s);

//							
					}
					kline.write(p + ".txt", DateUtil.getNowDateC());
				} catch (IOException e) {
					e.printStackTrace();
				}

//					System.out.println(f + " " + dataList.get(dataList.size() - 1));

			}
		}
		clearFiles();
	}

	public static void hurst() throws IOException {
		List<String> products = JavaFile.readfile("d:\\show2.txt");
		Map<String, Double[]> m = new HashMap<String, Double[]>();
		for (String s : products) {
			if (s.length() > 4) {
				String p = s.split(",")[0];

//				System.out.print(p + " ");
				List<String> klines = JavaFile.readfile("d:\\kline\\" + p + ".txt");

				double ks[] = new double[21];
				double ks1[] = new double[41];
				double ks2[] = new double[61];
				double ks3[] = new double[klines.size()];
				int i = 0;
				for (int k = klines.size() - 1; k >= 0; k--) {
					String kss = klines.get(k);
					if (i <= 20) {
						ks[i] = Double.parseDouble(kss.split(",")[1]);
					}
					if (i <= 40) {
						ks1[i] = Double.parseDouble(kss.split(",")[1]);
					}
					if (i <= 60) {
						ks2[i] = Double.parseDouble(kss.split(",")[1]);
					}
					ks3[i] = Double.parseDouble(kss.split(",")[1]);
					i++;
				}

				Double d[] = new Double[4];
				HurstResult result = HurstEx.hurst(ks);
				d[0] = Double.parseDouble(result.toString());
				result = HurstEx.hurst(ks1);
				d[1] = Double.parseDouble(result.toString());
				result = HurstEx.hurst(ks2);
				d[2] = Double.parseDouble(result.toString());
				result = HurstEx.hurst(ks3);
				d[3] = Double.parseDouble(result.toString());
				m.put(p, d);
			}
		}
		for (String t : m.keySet()) {
			System.out.println(t + " " + m.get(t)[0] + " " + m.get(t)[1] + " " + m.get(t)[2] + " " + m.get(t)[3]);
		}
	}

	public static void main(String[] args) throws IOException, InterruptedException {

//		getDataFromSina();
		writeDayKline();
		
//		group(DateUtil.getDatesTrading());
		group(DateUtil.getNowDateC());
//		hurst();
//		String path = "e:/tick"; // 要遍历的路径
//		File file = new File(path);
//
//		File[] files = file.listFiles(); // 遍历path下的文件和目录，放在File数组中
//		for (File f : files) {
//			if (f.isFile()) { // 若是文件，直接打印
////				if (f.getName().toString().length() < 11) {
//
////					File f4 = new File("d:/tick4/tick/" + f.getName());
////					File f3 = new File("d:/tick3/tick/" + f.getName());
////					File f2 = new File("d:/tick2/tick/" + f.getName());
////
////					String s = "";
////					if (f4.exists()) {
////						s = s + JavaFile.readfileToStringN("d:/tick4/tick/" + f.getName());
////					}
////					if (f3.exists()) {
////						s = s + JavaFile.readfileToStringN("d:/tick3/tick/" + f.getName());
////					}
////					if (f2.exists()) {
////						s = s + JavaFile.readfileToStringN("d:/tick2/tick/" + f.getName());
////					}
////					s = s + JavaFile.readfileToStringN(f.toString());
////					JavaFile.writefile("e:/tick/" + f.getName(), s);
////					System.out.println(f.toString());
////					timeLineAllInfo(JavaFile.readfile(f.toString()), f.getName());
//				KlineProcess k = new KlineProcess();
//				List<String> dates = JavaFile.readfile(f.toString());
//				String dateNow1 = "";
//				for (String s : dates) {
//					k.timeLineAllInfo(s);
//					String data[] = s.split(",");
//					String date = data[6];
////					if (Character.isUpperCase(f.getName().charAt(0))) {
////						int hour = Integer.parseInt(date.split("#")[1].split(":")[0]);
////						if (hour >= 15) {
////							dateNow1 = date.split("#")[0];
////							k.write(f.getName(), dateNow1);
////						}
////
////					} else {
////						if (!dateNow1.equals(date.split("#")[0])) {
////							dateNow1 = date.split("#")[0];
////							k.write(f.getName(), dateNow1);
////						}
////					}
//					if (!dateNow1.equals(date.split("#")[0])) {
//						dateNow1 = date.split("#")[0];
//						k.write(f.getName(), dateNow1);
//					}
//				}
//
//
//			}
//
//		}

	}

	private DescriptiveStatistics ds = new DescriptiveStatistics();
	private DescriptiveStatistics dsMinstep = new DescriptiveStatistics();

	double turnover = 0;
	double vol = 0;
	double interest = 0;
	double lastPrice = 0;
	double avaPrice = 0;
	public static String dateNow = "";

	public static void group(String sd) throws IOException, InterruptedException {

		Map<String, List<String>> groupMap = new HashMap<String, List<String>>();

		List<String> products = JavaFile.readfile("c:\\tick1\\name.txt");

		List<String> filters = new ArrayList<String>();

		List<String> options = new ArrayList<String>();
		for (String p : products) {
			if (!p.contains("(EF)") && !p.contains("TAS") && !p.contains("(EFP)") && !p.contains("efp")
					&& p.length() > 33) {
				options.add(p);
			}
		}

		for (String p : products) {
			if (filterProduct(p)) {
				filters.add(p);
			}
		}

		products.removeAll(filters);

		for (String p : products) {
			if (p.length() > 1) { // 若是文件，直接打印

				if (p.toString().length() < 12) {

					String code = p.replaceAll(".txt", "").replaceAll("\\d+", "");

					if (groupMap.get(code) == null) {
						List<String> l = new ArrayList<String>();
						l.add(p.replaceAll(".txt", ""));
						groupMap.put(code, l);
					} else {
						groupMap.get(code).add(p.replaceAll(".txt", ""));
					}

//					if (code.length() < 9) {
//						String cc = f.getName().replaceAll(".txt", "");
//
//						File file1 = new File("d:/kline/" + cc + ".txt");
//						if (!file1.exists()) {
//							Sina.get15mData(cc);
//							Thread.sleep(1000*5);
//						}
//
//					}

//					KlineProcess k = new KlineProcess();
//					List<String> dates = JavaFile.readfile(f.toString());
//					String dateNow1 = "";
//					for (String s : dates) {
//						k.timeLineAllInfo(s);
//						String data[] = s.split(",");
//						if (data.length < 7) {
//							continue;
//						}
//						String date = data[6];
//
//						if (!dateNow1.equals(date.split("#")[0])) {
//							dateNow1 = date.split("#")[0];
//							k.write(f.getName(), dateNow1);
//						}
//
//					}

				}

			}
		}

		Map<String, DescriptiveStatistics> highLowMap = new HashMap<String, DescriptiveStatistics>();
		Map<String, DescriptiveStatistics> atrMap = new HashMap<String, DescriptiveStatistics>();
		Map<String, DescriptiveStatistics> ma20Map = new HashMap<String, DescriptiveStatistics>();
		JavaFile.overwritefile("d:/group.txt", "");
		JavaFile.overwritefile("d:/show1.txt", "");
		JavaFile.overwritefile("d:/show2.txt", "");
		Set<String> set = groupMap.keySet();
		for (String s : set) {
			List<String> glist = groupMap.get(s);

			double highestVol = 0;
			String mainCode = "";
			for (String code : glist) {
				File fileKK = new File("d:/kline/" + code + ".txt");
				if (!fileKK.exists()) {
					continue;
				}

				List<String> datas = JavaFile.readfile("d:/kline/" + code + ".txt");

				int count = 0;
				if (datas.size() >= 20) {
					count = 20;
				} else {
					count = datas.size();
				}

				DescriptiveStatistics dsHighLow = new DescriptiveStatistics();
				DescriptiveStatistics dsATR = new DescriptiveStatistics();
				DescriptiveStatistics dsMA20 = new DescriptiveStatistics();
				String writeResult = "";
				for (int i = datas.size() - 1; i >= datas.size() - count; i--) {
					String data = datas.get(i);
					dsHighLow.addValue(Double.parseDouble(data.split(",")[2]));
					dsHighLow.addValue(Double.parseDouble(data.split(",")[3]));
					double tr = Double.parseDouble(data.split(",")[3]) - Double.parseDouble(data.split(",")[2]);

					if (i > 0 && Math.abs(Double.parseDouble(datas.get(i - 1).split(",")[1])
							- Double.parseDouble(data.split(",")[3])) > tr) {
						tr = Math.abs(Double.parseDouble(datas.get(i - 1).split(",")[1])
								- Double.parseDouble(data.split(",")[3]));
					}

					if (i > 0 && Math.abs(Double.parseDouble(datas.get(i - 1).split(",")[1])
							- Double.parseDouble(data.split(",")[2])) > tr) {
						tr = Math.abs(Double.parseDouble(datas.get(i - 1).split(",")[1])
								- Double.parseDouble(data.split(",")[2]));
					}

					dsATR.addValue(tr);
					dsMA20.addValue(Double.parseDouble(data.split(",")[1]));

					String result = data.split(",")[0] + "," + data.split(",")[1] + "," + data.split(",")[2] + ","
							+ data.split(",")[3] + "," + data.split(",")[4] + "," + data.split(",")[5] + ","
							+ data.split(",")[6] + "," + tr + "\r\n";

					writeResult = result + writeResult;
				}
				JavaFile.overwritefile("d:/kline1/" + code + ".txt", writeResult);
				highLowMap.put(code, dsHighLow);
				ma20Map.put(code, dsMA20);
				atrMap.put(code, dsATR);
				if (datas.size() == 0) {
					continue;
				}
				String data = datas.get(datas.size() - 1);

				if (data.split(",")[0].equals(sd)) {
					if (Double.parseDouble(data.split(",")[4]) > highestVol) {
						highestVol = Double.parseDouble(data.split(",")[4]);
						mainCode = code;
					}
				}
				JavaFile.writefile("d:/group.txt", code + ",");
			}

			List<String> datas = JavaFile.readfile("d:/kline/" + mainCode + ".txt");

			if (datas.size() >= 20) {
			} else {
				System.out.println(mainCode + "没有足够数据");
			}

			JavaFile.writefile("d:/group.txt", mainCode);
			JavaFile.writefile("d:/group.txt", "\r\n");
		}

		List<String> groupList = JavaFile.readfile("d:/group.txt");
		for (String g : groupList) {

			String gs[] = g.split(",");

			for (int i = 0; i < gs.length - 1; i++) {

				if (!gs[i].equals(gs[gs.length - 1])) {
					JavaFile.writefile("d:/show1.txt", gs[i] + "," + gs[i].replaceAll("\\d", "") + ",0,");
					JavaFile.writefile("d:/show1.txt", "," + highLowMap.get(gs[i]).getMax());
					JavaFile.writefile("d:/show1.txt", "," + highLowMap.get(gs[i]).getMin());
					JavaFile.writefile("d:/show1.txt", "," + atrMap.get(gs[i]).getMean());
					JavaFile.writefile("d:/show1.txt", "," + ma20Map.get(gs[i]).getMean());
					JavaFile.writefile("d:/show1.txt", ",\r\n");
				}

			}

		}

		for (String g : groupList) {

			String gs[] = g.split(",");

			if (!gs[gs.length - 1].equals("")
					&& ShowMeTheMoney2.unitMap.get(gs[gs.length - 1].replaceAll("\\d", "")) != null) {

//			List<String> sList = JavaFile.readfile("d:/kline/" + gs[gs.length - 1] + ".txt");

//			String dataKline = sList.get(sList.size() - 1);

//			if (Double.parseDouble(dataKline.split(",")[7]) <= 0
//					|| Double.parseDouble(dataKline.split(",")[8]) <= 0) {
//				System.out.println("unitMap.put(\"" + gs[gs.length - 1].replaceAll("\\d", "") + "\","
//						+ dataKline.split(",")[7] + ");");
//				System.out.println("minStepMap.put(\"" + gs[gs.length - 1].replaceAll("\\d", "") + "\","
//						+ dataKline.split(",")[8] + ");");
//
//			}

				String optionC = "";
				String optionP = "";
				double optionPriceHGap = 999999999;
				double optionPriceLGap = 999999999;
				for (String p : options) {
					if (p.length() > 1) { //  

						String startName = gs[gs.length - 1];
						if (gs[gs.length - 1].startsWith("IH")) {
							startName = gs[gs.length - 1].replaceAll("IH", "HO");
						} else if (gs[gs.length - 1].startsWith("IF")) {
							startName = gs[gs.length - 1].replaceAll("IF", "IO");
						} else if (gs[gs.length - 1].startsWith("IM")) {
							startName = gs[gs.length - 1].replaceAll("IM", "MO");
						}
						String tmpOptionName = p.replaceAll(startName, "");

//						if(startName.startsWith("PX") && p.startsWith(startName)) {
//							System.out.println("ss");
//						}

						if (p.startsWith(startName) && tmpOptionName.indexOf("C") >= 0) {

							double optionPrice = Math.abs(Double.parseDouble(
									tmpOptionName.replaceAll("C", "").replaceAll("-", "").replaceAll(".txt", ""))
									- highLowMap.get(gs[gs.length - 1]).getMax());
							if (optionPriceHGap > optionPrice) {
								optionPriceHGap = optionPrice;
								optionC = p;
							}

						}
						if (p.startsWith(startName) && tmpOptionName.indexOf("P") >= 0) {

							double optionPrice = Math.abs(Double
									.parseDouble(tmpOptionName.replaceAll("P", "").replaceAll("-", "")
											.replaceAll(".txt", "").replaceAll(gs[gs.length - 1], ""))
									- highLowMap.get(gs[gs.length - 1]).getMin());

							if (optionPriceLGap > optionPrice) {
								optionPriceLGap = optionPrice;
								optionP = p;
							}

						}

					}

				}

				double total = 2000;
//				if (optionC.replaceAll(".txt", "").length() > 0) {
//
//					if (optionC.startsWith("HO")) {
//						total = total * 2 / 3;
//					} else if (optionC.startsWith("IO")) {
//						total = total * 2 / 3;
//					} else if (optionC.startsWith("MO")) {
//						total = total;
//					} else {
//						total = total * 2;
//					}
//
//				}
				double position = 0;
				for (int i = 1; i < 100; i++) {
					position = i;
					if ((atrMap.get(gs[gs.length - 1]).getMean()
							* ShowMeTheMoney2.unitMap.get(gs[gs.length - 1].replaceAll("\\d", ""))) * i >= total) {
						break;
					}
				}
				position--;
//				if (position > 1000000) {
//					position = 0;
//				}
				System.out.print(gs[gs.length - 1] + " ");

//				Hurst.c(atrMap.get(gs[gs.length - 1]).getSortedValues());

				JavaFile.writefile("d:/show2.txt",
						gs[gs.length - 1] + "," + gs[gs.length - 1].replaceAll("\\d", "") + "," + (position) + ",");
				JavaFile.writefile("d:/show2.txt",
						optionC.replaceAll(".txt", "") + "#" + optionP.replaceAll(".txt", ""));
				JavaFile.writefile("d:/show2.txt", "," + highLowMap.get(gs[gs.length - 1]).getMax());
				JavaFile.writefile("d:/show2.txt", "," + highLowMap.get(gs[gs.length - 1]).getMin());
				JavaFile.writefile("d:/show2.txt", "," + atrMap.get(gs[gs.length - 1]).getMean());
				JavaFile.writefile("d:/show2.txt", "," + ma20Map.get(gs[gs.length - 1]).getMean());
				JavaFile.writefile("d:/show2.txt", ",\r\n");
			} else {
				// System.out.println("xxxxxxxxxxxxxx------------" + gs[gs.length - 1]);
			}
		}
	}

	public void timeLineAllInfo(String s) {

		String data[] = s.split(",");
		if (data.length < 7) {
			return;
		}
		String date = data[6];
		String code = data[0];
		if (dateNow.equals("") && code.startsWith("cu")) {
			dateNow = date.split("#")[0];
		}

		turnover = Double.parseDouble(data[9]) / 10000;
		vol = Double.parseDouble(data[10]);
		interest = Double.parseDouble(data[11]);
		lastPrice = Double.parseDouble(data[14]);
		avaPrice = Double.parseDouble(data[13]);

		if (lastPrice <= 0) {
			return;
		}

		BigDecimal bd = BigDecimal.valueOf(Double.parseDouble(data[2]));
		BigDecimal bd2 = BigDecimal.valueOf(Double.parseDouble(data[3]) * -1);
//		bd.divide(bd2,BigDecimal.ROUND_HALF_DOWN);
		bd = bd.add(bd2);
		dsMinstep.addValue(bd.doubleValue());
		ds.addValue(lastPrice);

//			System.out.println(date + " " + turnover / 10000 + " " + interest + " " + lastPrice + " " + ds.getMax()
//					+ " " + ds.getMin());

	}

	public void write(String fileName, String dateN) throws IOException {
		if (ds.getN() > 0) {
			StringBuffer sb = new StringBuffer();
			File file = new File("d:/kline/" + fileName);
			if (file.exists()) {
				List<String> list = JavaFile.readfile("d:/kline/" + fileName);
				for (int i = 0; i < list.size(); i++) {
					sb.append(list.get(i) + "\r\n");
				}
			}

			String result = sb.toString() + dateN + "," + ds.getElement((int) (ds.getN() - 1)) + "," + ds.getMin() + ","
					+ ds.getMax() + "," + turnover + "," + vol + "," + interest;
//			System.out.println(result);
			JavaFile.overwritefile("d:/kline/" + fileName, result + "\r\n");
			ds = new DescriptiveStatistics();
		}
	}

}
